<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\pt\controller;

use think\admin\Controller;
use think\facade\Db;

/**
 * Class Order
 * @package app\group\controller
 */
class Order extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'PtTopOrder';

    /**
     * 订单列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '订单列表';
        $group_list = $this->app->db->name('PtGroupAct')->where([['is_forbid', '=', 0], ['group_status', '<>', 0]])->order('add_time desc')->select()->toArray();
        // array_unshift($group_list, ['id' => 0, 'pro_name' => '全部']);
        $this->assign('group_list', $group_list);
        $this->assign('order_status', config('base.order_status'));
        $this->_query($this->table)->dateBetween('pay_time')
            ->page();

    }

    /**
     * 订单详情
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderDetail()
    {
        $this->title = '订单详情';
        $top_id = $this->request->get('id', '', 'int');
        $order_info = Db::table('pt_top_order')
             ->where(['top_id' => $top_id])->findOrEmpty();
        if (empty($order_info)) $this->error('未找到该订单');
        $user_info = get_user_info(1, ['id' => $order_info['user_id']]);

        $this->assign('user_info', $user_info);
        $order_info['pay_time_name'] = getPayName($order_info['pay_type']);

        // $order_info['score_money'] = $order_info['score'] / 100;

        // $address_info = Db::table('pt_order_addr')->where(['top_id' => $top_id])->findOrEmpty();
        $group_info = Db::table('pt_group_act')->where(['id' => $order_info['group_id']])->findOrEmpty();
        // $return_info = Db::table('pt_refund')->where(['top_id' => $top_id])->findOrEmpty();

        $this->assign('pay_type', config('base.pay_type'));
        $this->assign('trans_type', config('base.trans_type'));
        $this->assign('order_status', config('base.order_status'));
        $this->assign('order_info', $order_info);

        $this->assign('group_info', $group_info);
        
        // $this->assign('address_info', $address_info);
        // $this->assign('return_info', $return_info ?: []);
        $this->assign('apply_list', config('base.apply_list'));
        $this->assign('reason_list', config('base.reason_list'));
        $this->fetch();
    }

    /**
     * 订单发货
     * @auth true
     */
    public function sendGoods()
    {
        $trams_types = config('base.trans_type');
        if ($this->request->isPost()) {
            $data = $this->_vali([
                'top_id.require|number' => '缺少参数 top_id',
                'trans_type.require|number' => '缺少参数 trans_type',
                'trans_no.require|max:20' => '缺少参数 trans_no 或 长度过长',
            ]);
            $trans_ids = array_keys($trams_types);
            if (!in_array($data['trans_type'], $trans_ids)) $this->error('物流类型错误');
            $Model = $this->app->db;
            $top_info = $bool = $Model->name('pt_son_order')->where([
                'top_id' => $data['top_id'], 'order_status' => 2
            ])->find();
            if (empty($top_info)) $this->error('订单不存在');
            $Model->startTrans();
            try {
                $bool = $Model->name('pt_son_order')->where([
                    'top_id' => $data['top_id'], 'order_status' => 2
                ])->save(['order_status' => 3]);
                if (!$bool) $this->error('发货失败 001');
                $bool = $Model->name('pt_order_addr')->where([
                    'top_id' => $data['top_id']
                ])->save([
                    'trans_type' => $data['trans_type'],
                    'trans_no' => $data['trans_no'],
                    'send_time' => date('Y-m-d H:i:s'),
                    'receive_time_end' => date('Y-m-d H:i:s', strtotime('+7 day')),
                ]);
                if (!$bool) $this->error('发货失败 002');
                $Model->commit();
            } catch (\Exception $e) {
                $Model->rollback();
                $this->error($e->getMessage());
            }
            $this->success('发货成功');
        }
        $this->assign('trams_types', $trams_types);
        $this->fetch();
    }

    /**
     * 退款订单列表
     * @auth true
     * @menu true
     */
    public function returnOrderList()
    {
        $this->title = '退款列表';
        $group_list = $this->app->db->name('PtGroupAct')->where([['is_forbid', '=', 0], ['group_status', '<>', 0]])->order('add_time desc')->select()->toArray();
        array_unshift($group_list, ['id' => 0, 'pro_name' => '全部']);
        $this->assign('group_list', $group_list);
        $this->assign('status', [0 => '待处理', 1 => '退款驳回', 2 => '退款完成']);
        $this->_query('pt_refund')->alias('a')
            ->field('a.*,b.top_no,b.pay_time,b.pay_type,c.pro_name,c.order_status,c.real_pay,c.score,c.num,c.pro_spec,d.name,d.mobile')
            ->join('pt_top_order b', 'a.top_id = b.top_id')
            ->join('pt_son_order c', 'a.top_id = c.top_id')
            ->join('pt_order_addr d', 'a.top_id = d.top_id')
            ->equal('c.group_id,a.status')
            ->like('c.pro_name')
            ->dateBetween('a.add_time')
            ->page();
    }

    /**
     * 确认退款  qwerty0925!
     */
    public function confirmReturn()
    {
        $return_id = $this->request->post('id', '', 'int');
        $money = $this->request->post('money', '', 'float');
        $password = $this->request->post('password', '', 'string');
        if (empty($return_id) || empty($password) || !isset($money) || !is_numeric($money)) $this->error('缺少必要参数~');
        //echo sp_password($password);exit;
        if (sp_password($password) != '###9b1e28ab50333bc03fdcb3dac9681f73') $this->error('密码不正确');
        $return_info = OrderService::instance()->doConfirmReturn($return_id, $money, 1);
        if ($return_info['code'] == 1) {
            $this->success('退款处理成功');
        } else {
            $this->error($return_info['info']);
        }

    }


}